package com.xywh.wanandroid.data.repository.datasource

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.xywh.wanandroid.data.model.bean.ProjectTreeItem
import com.xywh.wanandroid.network.apiService

class ProjectTreeDataSource() : PagingSource<Int, ProjectTreeItem>() {

    override fun getRefreshKey(state: PagingState<Int, ProjectTreeItem>): Int? {
        // 根据preKey和nextKey中找到离anchorPosition最近页面的键值
        // Try to find the page key of the closest page to anchorPosition from
        // either the prevKey or the nextKey; you need to handle nullability
        // here.
        //  * prevKey == null -> anchorPage is the first page.
        //  * nextKey == null -> anchorPage is the last page.
        //  * both prevKey and nextKey are null -> anchorPage is the
        //    initial page, so return null.
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }

    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ProjectTreeItem> {
        // 定义键值
        val currentKey = params.key ?: 0
        return try {
            val response = apiService.getProjectTree()
            val datas = response.data
            LoadResult.Page(
                data = datas,
                prevKey = null,
                nextKey = null
            )
        } catch (exception: Exception) {
            LoadResult.Error(exception)
        }
    }
}